import { loginAPI } from "../../apis/user"

const TOKEN_KEY = 'token_key'
const USERINFO_KEY = 'userinfor_keyh'

export default {
    namespaced: true,
    state:()=>{
        return {
            token: uni.getStorageSync(TOKEN_KEY) ||'',
            userInfo:uni.getStorageSync(USERINFO_KEY) || {},
            testData:'iamtext'
        }
    },
    mutations:{
        setUserInfo(state,val){
            state.userInfo = val
            this.commit('user/saveUserInfoToLocal',state.userInfo)
        },
        saveUserInfoToLocal(state,val){
            uni.setStorage({
                key: USERINFO_KEY,
                data: val,
            })
        },
        setToken(state,val){
            state.token = val
            this.commit('user/saveTokenToLocal',state.token)
        },
        saveTokenToLocal(state,val){
            uni.setStorage({
                key:TOKEN_KEY,
                data:val
            })
        }
        
    },
    actions:{

        async getUserinfo(context,val){
            // console.log('iamUserStore');
            // console.log(val);
            //  console.log(res);
            const userInfo = val.userInfo
            const obj = {
                signature:val.signature,
                iv:val.iv,
                nickName:userInfo.nickName,
                gender:userInfo.gender,
                city:userInfo.city,
                province:userInfo.province,
                avatarUrl:userInfo.avatarUrl
            }
            const {data:res}  = await loginAPI(obj)
            // console.log(res);
            this.commit('user/setToken',res.token)
            this.commit('user/setUserInfo',userInfo)

        },
        logOut(context){
            this.commit('user/setUserInfo',{})
            this.commit('user/setToken','')
        },
        /**
         * 用户登录判定
         */
        async isLogin(context){
            if(context.state.token){
                return true
            }else{
                await uni.showModal({
                    title: '用户未登录',
                    content: '请登录后再进行后续操作',
                    showCancel: true,
                    success: ({ confirm, cancel }) => {
                        if(confirm){
                            uni.navigateTo({ url: '/subpkg/pages/login-page/login-page' })
                        }
                    }
                })
                return false
            }

        }
    }
}